package pl.nazaweb.samplesandtutorials;

import java.util.ArrayList;
import java.util.List;

import pl.nazaweb.samplesandtutorials.abstracts.ShopList;
import pl.nazaweb.samplesandtutorials.adapters.ShopListAdapter;
import pl.nazaweb.samplesandtutorials.adapters.ShopListItem;
import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class CheckedListViewExample extends ListActivity {

	List<String> itemList = new ArrayList();
	ListView checkList;
	Button checkedButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checked_list_view_example);
		checkList = getListView();
		initShopList();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, itemList);
		checkList.setAdapter(adapter);
		checkList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		
		checkedButton = (Button)findViewById(R.id.get_checked_items_in_check_list_view_button);
		checkedButton.setOnClickListener(getCheckedButtonOnClickListener());
	}
	
	private OnClickListener getCheckedButtonOnClickListener(){
		return new OnClickListener() {
			public void onClick(View v) {
				if(checkList.getAdapter().hasStableIds()==true){
					long[] items = checkList.getCheckedItemIds();
					for(long id : items){
						Log.v("item>>", itemList.get((int) id));
					}
				}else{
					Log.v("", "niestablnej idiki w adapterze");
				}
			}
		};
	}

	private void initShopList() {
		ShopList shopList = new ShopList();
		Uri allShopItems = shopList.getContentUri();
		Cursor cur = managedQuery(allShopItems, null, null, null, null);
		for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
			itemList.add(cur.getString(1));
		}
		cur.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.checked_list_view_example, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
